﻿using System;
using System.Text;
using System.Collections.Specialized;
using Newtonsoft.Json;

namespace CometDocs
{
    internal partial class Client
    {
        /// <summary>
        /// Download a file from CometDocs storage to local memory: https://www.cometdocs.com/developer/apiDocumentation#method-downloadFile
        /// </summary>
        /// <param name="token">A valid authentication token.</param>
        /// <param name="file">The file to download.</param>
        /// <returns>A File instance with the file content.</returns>
        public File DownloadFile(AuthenticationToken token, FileInfo file)
        {
            NameValueCollection @params = new NameValueCollection(2);
            @params.Add("token", token.Value);
            @params.Add("id", file.ID.ToString());

            byte[] result = webClient.UploadValues(APIRoot + "downloadFile", @params);

            string contentType = webClient.ResponseHeaders["content-type"];

            // In case of error the response payload is not the file content but an error object.
            if (contentType == "text/json")
            {
                string json = Encoding.ASCII.GetString(result);

                Response response = JsonConvert.DeserializeObject<Response>(json);

                CheckAndThrow(response);

                throw new Exception(string.Format("Response is json but it seems to be valid: {0}!", json));
            }

            return new File
            {
                ID = file.ID,
                Name = file.Name,
                Extension = file.Extension,
                Size = file.Size,
                HasConversions = file.HasConversions,
                Content = result
            };
        }
    }
}
